package com.snowfield.lb47.lbconfig.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.Seq;
import com.snowfield.lb47.lbconfig.domain.FrontProxyCrt;
import com.snowfield.lb47.lbconfig.mapper.FrontProxyCrtMapper;
import com.snowfield.lb47.lbconfig.service.IFrontProxyCrtService;
import com.snowfield.lbcommon.config.SnowFieldConfig;
import com.snowfield.lbcommon.utils.commonsexec.CommonExecutor;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 代理证书Service业务层处理
 *
 * @author snowfield
 * @date 2024-04-09
 */
@Service
public class FrontProxyCrtServiceImpl implements IFrontProxyCrtService {
    @Autowired
    private FrontProxyCrtMapper frontProxyCrtMapper;

    /**
     * 查询代理证书
     *
     * @param id 代理证书主键
     * @return 代理证书
     */
    @Override
    public FrontProxyCrt selectFrontProxyCrtById(Long id) {
        FrontProxyCrt frontProxyCrt = frontProxyCrtMapper.selectFrontProxyCrtById(id);
        if ("upload".equals(frontProxyCrt.getCreateType())) {
            if (new File(frontProxyCrt.getCrtPath()).exists()) {
                try {
                    String pemContent = FileUtils.readFileToString(new File(frontProxyCrt.getCrtPath()), StandardCharsets.UTF_8);
                    frontProxyCrt.setPemContent(pemContent);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return frontProxyCrt;
    }

    /**
     * 查询代理证书列表
     *
     * @param frontProxyCrt 代理证书
     * @return 代理证书
     */
    @Override
    public List<FrontProxyCrt> selectFrontProxyCrtList(FrontProxyCrt frontProxyCrt) {
        List<FrontProxyCrt> list = frontProxyCrtMapper.selectFrontProxyCrtList(frontProxyCrt);
        //处理证书路径信息，不向前端展示
        for (FrontProxyCrt proxyCrt : list) {
            if (StringUtils.isEmpty(proxyCrt.getCrtPath())) {
                proxyCrt.setCrtPath("0");
            } else {
                proxyCrt.setCrtPath("1");
            }
        }
        return list;
    }

    /**
     * 新增代理证书
     *
     * @param frontProxyCrt 代理证书
     * @return 结果
     */
    @Override
    public int insertFrontProxyCrt(FrontProxyCrt frontProxyCrt) {
        frontProxyCrt.setCreateTime(DateUtils.getNowDate());
        String seqId = Seq.getId(Seq.uploadSeqType);
        String crtFileName = StringUtils.format("{}_{}.{}", "proxyPem", seqId, "pem");
        String crtPath = SnowFieldConfig.getProxyCrtPath() + "/" + crtFileName;
        if ("upload".equals(frontProxyCrt.getCreateType())) {
            try {
                FileUtils.write(new File(crtPath), frontProxyCrt.getPemContent(), StandardCharsets.UTF_8);
                frontProxyCrt.setCrtPath(crtPath);
            } catch (IOException e) {
                e.printStackTrace();
                return 0;
            }
        } else if ("create".equals(frontProxyCrt.getCreateType())) {
            return 0;
        }

        Integer affectRows = frontProxyCrtMapper.insertFrontProxyCrt(frontProxyCrt);
        return affectRows;
    }

    /**
     * 修改代理证书
     *
     * @param frontProxyCrt 代理证书
     * @return 结果
     */
    @Override
    public int updateFrontProxyCrt(FrontProxyCrt frontProxyCrt) {
        frontProxyCrt.setUpdateTime(DateUtils.getNowDate());
        String crtPath = frontProxyCrt.getCrtPath();
        //如果原来证书文件未正确生成时
        if (StringUtils.isEmpty(crtPath)) {
            String seqId = Seq.getId(Seq.uploadSeqType);
            String crtFileName = StringUtils.format("{}_{}.{}", "proxyPem", seqId, "pem");
            crtPath = SnowFieldConfig.getProxyCrtPath() + "/" + crtFileName;
        }
        if ("upload".equals(frontProxyCrt.getCreateType())) {
            try {
                FileUtils.write(new File(crtPath), frontProxyCrt.getPemContent(), StandardCharsets.UTF_8);
                frontProxyCrt.setCrtPath(crtPath);
            } catch (IOException e) {
                e.printStackTrace();
                return 0;
            }
        } else if ("create".equals(frontProxyCrt.getCreateType())) {
            return 0;
        }
        Integer affectRows = frontProxyCrtMapper.updateFrontProxyCrt(frontProxyCrt);
        return affectRows;
    }

    /**
     * 批量删除代理证书
     *
     * @param ids 需要删除的代理证书主键
     * @return 结果
     */
    @Override
    public int deleteFrontProxyCrtByIds(Long[] ids) {
        for (Long id : ids) {
            FrontProxyCrt frontProxyCrt = frontProxyCrtMapper.selectFrontProxyCrtById(id);
            String crtPath = frontProxyCrt.getCrtPath();
            if (new File(crtPath).exists()) {
                FileUtils.deleteQuietly(new File(crtPath));
            }
        }

        return frontProxyCrtMapper.deleteFrontProxyCrtByIds(ids);
    }

    /**
     * 删除代理证书信息
     *
     * @param id 代理证书主键
     * @return 结果
     */
    @Override
    public int deleteFrontProxyCrtById(Long id) {
        FrontProxyCrt frontProxyCrt = frontProxyCrtMapper.selectFrontProxyCrtById(id);
        String crtPath = frontProxyCrt.getCrtPath();
        if (new File(crtPath).exists()) {
            FileUtils.deleteQuietly(new File(crtPath));
        }

        return frontProxyCrtMapper.deleteFrontProxyCrtById(id);
    }

    /**
     * 校验证书名称是否唯一
     *
     * @param frontProxyCrt 证书
     * @return 结果
     */
    @Override
    public Boolean checkNameUnique(FrontProxyCrt frontProxyCrt) {
        Long crtId = frontProxyCrt.getId();
        FrontProxyCrt crt = frontProxyCrtMapper.selectFrontProxyCrtByName(frontProxyCrt.getCrtName());
        if (crt != null && !crt.getId().equals(crtId)) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

}
